// pages/FeynmanRecordPage.jsx
import { useState, useRef, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import apiClient from '../api/axios';
import LoadingSpinner from '../components/LoadingSpinner';

// 简单的Markdown到HTML转换函数
const markdownToHtml = (markdown) => {
  if (!markdown) return '';
  
  let html = markdown;
  
  // 转换粗体 **text**
  html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // 转换粗体 __text__
  html = html.replace(/__(.*?)__/g, '<strong>$1</strong>');
  
  // 转换斜体 *text*
  html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
  
  // 转换斜体 _text_
  html = html.replace(/_(.*?)_/g, '<em>$1</em>');
  
  // 转换标题 # 标题
  html = html.replace(/^# (.*$)/gm, '<h1>$1</h1>');
  html = html.replace(/^## (.*$)/gm, '<h2>$1</h2>');
  html = html.replace(/^### (.*$)/gm, '<h3>$1</h3>');
  
  // 转换无序列表项 - item
  html = html.replace(/^- (.*$)/gm, '<li>$1</li>');
  
  // 将连续的<li>包装在<ul>中
  html = html.replace(/(<li>.*<\/li>)+/gs, (match) => {
    return `<ul>${match}</ul>`;
  });
  
  // 处理缩进列表项（4个空格或一个制表符）
  html = html.replace(/^(\s{4}|\t)(.*$)/gm, '<ul><li>$2</li></ul>');
  
  // 转换换行符
  html = html.replace(/\n/g, '<br>');
  
  return html;
};

function FeynmanRecordPage() {
    const { id } = useParams();
    const navigate = useNavigate();
    const [isRecording, setIsRecording] = useState(false);
    const [audioUrl, setAudioUrl] = useState(null);
    const [audioBlob, setAudioBlob] = useState(null);
    const [transcription, setTranscription] = useState('');
    const [isTranscribing, setIsTranscribing] = useState(false);
    const [aiFeedback, setAiFeedback] = useState(null);
    const [isEvaluating, setIsEvaluating] = useState(false);
    const [error, setError] = useState('');
    const [knowledgePoint, setKnowledgePoint] = useState(null);
    const [loading, setLoading] = useState(true);
    
    const mediaRecorderRef = useRef(null);
    const audioChunksRef = useRef([]);
    const mediaStreamRef = useRef(null);

    // 获取知识点信息
    useEffect(() => {
        const fetchKnowledgePoint = async () => {
            try {
                const response = await apiClient.get(`/knowledge-points/${id}`);
                setKnowledgePoint(response.data);
                setLoading(false);
            } catch (err) {
                console.error('获取知识点失败:', err);
                setError('获取知识点失败: ' + err.message);
                setLoading(false);
            }
        };

        if (id) {
            fetchKnowledgePoint();
        } else {
            setLoading(false);
        }
    }, [id]);

    // 开始录音
    const startRecording = async () => {
        try {
            console.log('请求访问麦克风...');
            // 优化录音参数以提高音频质量
            const stream = await navigator.mediaDevices.getUserMedia({ 
                audio: {
                    echoCancellation: true,
                    noiseSuppression: true,
                    autoGainControl: true,
                    channelCount: 1,
                    sampleRate: 44100,  // 提高采样率
                    sampleSize: 16      // 提高采样精度
                } 
            });
            console.log('麦克风访问成功');
            
            mediaStreamRef.current = stream;
            
            // 使用更高质量的音频格式
            const mimeType = 'audio/webm;codecs=opus';
            mediaRecorderRef.current = new MediaRecorder(stream, { mimeType });
            audioChunksRef.current = [];

            mediaRecorderRef.current.ondataavailable = (event) => {
                console.log('录音数据可用:', event.data.size, '字节');
                audioChunksRef.current.push(event.data);
            };

            mediaRecorderRef.current.onstop = () => {
                console.log('录音停止');
                const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/webm;codecs=opus' });
                console.log('创建音频Blob:', audioBlob.size, '字节, 类型:', audioBlob.type);
                const audioUrl = URL.createObjectURL(audioBlob);
                setAudioUrl(audioUrl);
                setAudioBlob(audioBlob);
                console.log('音频URL创建成功');
            };

            mediaRecorderRef.current.start(1000); // 每秒触发一次dataavailable事件
            console.log('开始录音');
            setIsRecording(true);
            setError('');
        } catch (err) {
            console.error('录音错误:', err);
            setError('无法访问麦克风，请检查权限设置: ' + err.message);
        }
    };

    // 停止录音
    const stopRecording = () => {
        if (mediaRecorderRef.current && isRecording) {
            console.log('停止录音');
            mediaRecorderRef.current.stop();
            // 停止所有音轨
            if (mediaStreamRef.current) {
                mediaStreamRef.current.getTracks().forEach(track => {
                    console.log('停止音轨:', track.kind);
                    track.stop();
                });
            }
            setIsRecording(false);
        }
    };

    // 上传并转录音频
    const transcribeAudio = async () => {
        if (!audioUrl || !audioBlob) {
            setError('请先录制音频');
            return;
        }

        try {
            console.log('开始转录音频...');
            setIsTranscribing(true);
            setError('');
            
            // 创建FormData
            const formData = new FormData();
            formData.append('audio', audioBlob, 'recording.webm');
            
            console.log('发送转录请求到后端API...');
            console.log('API地址:', '/api/unified-asr/transcribe');

            // 发送到统一ASR API
            const response = await apiClient.post('/unified-asr/transcribe', formData, {
                timeout: 30000 // 30秒超时
            });

            console.log('收到转录响应:', response.status, response.data);
            setTranscription(response.data.result);
            
            // 转录成功后自动触发AI评价
            if (response.data.result && knowledgePoint) {
                getAiEvaluation(response.data.result);
            }
            
            console.log('转录完成');
        } catch (err) {
            console.error('转录错误:', err);
            
            let errorMessage = '转录失败: ';
            if (err.response) {
                errorMessage += `服务器错误 ${err.response.status}: ${err.response.statusText}`;
                if (err.response.data) {
                    errorMessage += ` - ${JSON.stringify(err.response.data)}`;
                }
            } else if (err.request) {
                errorMessage += '无法连接到服务器，请检查网络连接和服务状态';
            } else {
                errorMessage += err.message;
            }
            
            setError(errorMessage);
        } finally {
            setIsTranscribing(false);
        }
    };

    // 获取AI评价
    const getAiEvaluation = async (transcribedText) => {
        // 检查转录文本是否有效
        if (!transcribedText || transcribedText.trim().length < 5) {
            setError('转录文本太短或无效，无法进行AI评价');
            setIsEvaluating(false);
            return;
        }

        setIsEvaluating(true);
        setAiFeedback(null);
        try {
            const originalContent = knowledgePoint ? knowledgePoint.content : '未提供知识点内容';
            
            const feedbackResponse = await apiClient.post('/ai/evaluate', {
                originalContent: originalContent,
                transcribedText: transcribedText
            });

            setAiFeedback(feedbackResponse.data);
        } catch (error) {
            console.error('获取AI评价失败', error);
            setError('获取AI评价失败: ' + (error.response?.data?.message || error.message));
            
            // 显示转录文本以便用户了解问题
            setAiFeedback({
                polishedAnswer: transcribedText,
                evaluation: "由于转录文本质量较低，AI无法进行准确评价。请尝试在更安静的环境中重新录音，或检查麦克风设置。",
                strengths: [],
                weaknesses: ["转录文本质量较低", "无法进行准确分析"],
                score: 0
            });
        } finally {
            setIsEvaluating(false);
        }
    };

    // 渲染富文本内容的函数
    const renderRichText = (content) => {
        // 如果内容包含HTML标签，则直接渲染
        if (content && /<[a-z][\s\S]*>/i.test(content)) {
            return { __html: content };
        } 
        // 如果内容看起来像Markdown，则转换为HTML
        else if (content && (content.includes('**') || content.includes('__') || content.includes('*') || content.includes('_') || content.includes('#'))) {
            return { __html: markdownToHtml(content) };
        }
        // 对于纯文本内容，处理换行符
        else {
            // 简单的HTML转义处理，防止XSS攻击
            const escapeHtml = (text) => {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            };
            return { __html: escapeHtml(content).replace(/\n/g, '<br>') };
        }
    };

    if (loading) {
        return (
            <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
                <div style={{ 
                    display: 'flex', 
                    justifyContent: 'space-between', 
                    alignItems: 'center', 
                    marginBottom: '1rem' 
                }}>
                    <h1>🧠 费曼学习法 - 复述练习</h1>
                    <button 
                        onClick={() => navigate('/')} 
                        style={{ 
                            padding: '8px 16px', 
                            backgroundColor: '#6c757d', 
                            color: 'white', 
                            border: 'none', 
                            borderRadius: '4px', 
                            cursor: 'pointer'
                        }}
                    >
                        ← 返回主页
                    </button>
                </div>
                <LoadingSpinner message="加载知识点中..." useGame={true} />
            </div>
        );
    }

    if (isEvaluating) {
        return (
            <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
                <div style={{ 
                    display: 'flex', 
                    justifyContent: 'space-between', 
                    alignItems: 'center', 
                    marginBottom: '1rem' 
                }}>
                    <h1>🧠 费曼学习法 - 复述练习</h1>
                    <button 
                        onClick={() => navigate('/')} 
                        style={{ 
                            padding: '8px 16px', 
                            backgroundColor: '#6c757d', 
                            color: 'white', 
                            border: 'none', 
                            borderRadius: '4px', 
                            cursor: 'pointer'
                        }}
                    >
                        ← 返回主页
                    </button>
                </div>
                {knowledgePoint && (
                    <div style={{ 
                        marginBottom: '20px', 
                        padding: '20px', 
                        backgroundColor: '#e3f2fd', 
                        borderRadius: '8px',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                        <h2>知识点: {knowledgePoint.title}</h2>
                        <div style={{ marginTop: '15px' }}>
                            <strong>内容:</strong>
                        </div>
                        <div 
                            style={{ 
                                backgroundColor: 'white', 
                                padding: '20px', 
                                borderRadius: '4px',
                                border: '1px solid #ddd',
                                maxHeight: '400px',
                                overflowY: 'auto',
                                marginTop: '10px',
                                lineHeight: '1.6'
                            }}
                            dangerouslySetInnerHTML={renderRichText(knowledgePoint.content)}
                        />
                    </div>
                )}
                <LoadingSpinner message="AI教练正在批阅您的答卷..." useGame={true} />
            </div>
        );
    }

    return (
        <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
            <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center', 
                marginBottom: '1rem' 
            }}>
                <h1 style={{ margin: 0 }}>🧠 费曼学习法 - 复述练习</h1>
                <button 
                    onClick={() => navigate('/')} 
                    style={{ 
                        padding: '8px 16px', 
                        backgroundColor: '#6c757d', 
                        color: 'white', 
                        border: 'none', 
                        borderRadius: '4px', 
                        cursor: 'pointer'
                    }}
                >
                    ← 返回主页
                </button>
            </div>
            
            {knowledgePoint && (
                <div style={{ 
                    marginBottom: '20px', 
                    padding: '20px', 
                    backgroundColor: '#e3f2fd', 
                    borderRadius: '8px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}>
                    <h2>知识点: {knowledgePoint.title}</h2>
                    <div style={{ marginTop: '15px' }}>
                        <strong>内容:</strong>
                    </div>
                    <div 
                        style={{ 
                            backgroundColor: 'white', 
                            padding: '20px', 
                            borderRadius: '4px',
                            border: '1px solid #ddd',
                            maxHeight: '400px',
                            overflowY: 'auto',
                            marginTop: '10px',
                            lineHeight: '1.6'
                        }}
                        dangerouslySetInnerHTML={renderRichText(knowledgePoint.content)}
                    />
                </div>
            )}

            <div style={{ 
                marginBottom: '20px',
                padding: '20px',
                backgroundColor: '#f8f9fa',
                borderRadius: '8px',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
            }}>
                <h2>🎤 录音控制</h2>
                <div style={{ 
                    display: 'flex', 
                    gap: '15px', 
                    flexWrap: 'wrap',
                    marginBottom: '15px'
                }}>
                    <button 
                        onClick={startRecording} 
                        disabled={isRecording}
                        style={{ 
                            padding: '12px 24px', 
                            backgroundColor: isRecording ? '#9e9e9e' : '#4CAF50', 
                            color: 'white', 
                            border: 'none', 
                            borderRadius: '4px', 
                            cursor: isRecording ? 'not-allowed' : 'pointer',
                            fontSize: '16px',
                            fontWeight: 'bold'
                        }}
                    >
                        {isRecording ? '⏹️ 停止录音' : '⏺️ 开始录音'}
                    </button>
                    {isRecording && (
                        <button 
                            onClick={stopRecording} 
                            style={{ 
                                padding: '12px 24px', 
                                backgroundColor: '#f44336', 
                                color: 'white', 
                                border: 'none', 
                                borderRadius: '4px', 
                                cursor: 'pointer',
                                fontSize: '16px',
                                fontWeight: 'bold'
                            }}
                        >
                            ⏹️ 停止录音
                        </button>
                    )}
                    
                    {audioUrl && (
                        <button 
                            onClick={transcribeAudio} 
                            disabled={isTranscribing}
                            style={{ 
                                padding: '12px 24px', 
                                backgroundColor: isTranscribing ? '#9e9e9e' : '#2196F3', 
                                color: 'white', 
                                border: 'none', 
                                borderRadius: '4px', 
                                cursor: isTranscribing ? 'not-allowed' : 'pointer',
                                fontSize: '16px',
                                fontWeight: 'bold'
                            }}
                        >
                            {isTranscribing ? '🔄 转录中...' : '📝 转录音频'}
                        </button>
                    )}
                </div>
                
                <div style={{ 
                    backgroundColor: '#e9ecef', 
                    padding: '15px', 
                    borderRadius: '4px'
                }}>
                    <h3 style={{ marginTop: 0 }}>使用说明</h3>
                    <ul style={{ marginBottom: 0 }}>
                        <li>仔细阅读知识点内容</li>
                        <li>点击"开始录音"按钮开始复述知识点</li>
                        <li>点击"停止录音"按钮结束录制</li>
                        <li>点击"转录音频"按钮将录制的音频发送到阿里云ASR服务进行转录</li>
                        <li>转录完成后，AI教练会自动对您的复述进行评价和打分</li>
                    </ul>
                </div>
            </div>

            {audioUrl && (
                <div style={{ 
                    marginBottom: '20px',
                    padding: '20px',
                    backgroundColor: '#f8f9fa',
                    borderRadius: '8px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}>
                    <h2>🔊 录制的音频</h2>
                    <audio src={audioUrl} controls style={{ width: '100%' }} />
                </div>
            )}

            {transcription && (
                <div style={{ 
                    marginBottom: '20px',
                    padding: '20px',
                    backgroundColor: '#f8f9fa',
                    borderRadius: '8px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}>
                    <h2>📄 转录结果</h2>
                    <div style={{ 
                        padding: '15px', 
                        backgroundColor: '#fff', 
                        borderRadius: '4px',
                        border: '1px solid #ddd',
                        whiteSpace: 'pre-wrap',
                        lineHeight: '1.6'
                    }}>
                        {transcription}
                    </div>
                </div>
            )}

            <hr style={{ margin: '30px 0', borderColor: '#ddd' }} />

            <h2>🤖 AI 教练反馈:</h2>
            {aiFeedback && (
                <div className="ai-feedback" style={{ 
                    display: 'flex', 
                    gap: '2rem',
                    padding: '20px',
                    backgroundColor: '#f8f9fa',
                    borderRadius: '8px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}>
                    <div style={{ flex: 1 }}>
                        <h3>✨ AI 润色后的文本</h3>
                        <div style={{ 
                            background: '#fff', 
                            padding: '1rem',
                            borderRadius: '4px',
                            border: '1px solid #ddd',
                            marginBottom: '20px',
                            lineHeight: '1.6'
                        }}>
                            {aiFeedback.polishedAnswer}
                        </div>
                        
                        <h3>📊 综合评价</h3>
                        <p style={{ 
                            padding: '15px', 
                            backgroundColor: '#fff',
                            borderRadius: '4px',
                            border: '1px solid #ddd',
                            lineHeight: '1.6'
                        }}>
                            {aiFeedback.evaluation}
                        </p>

                        <div style={{ display: 'flex', gap: '20px', marginTop: '20px' }}>
                            <div style={{ flex: 1 }}>
                                <h3>👍 优点</h3>
                                <ul style={{ 
                                    padding: '15px', 
                                    backgroundColor: '#fff',
                                    borderRadius: '4px',
                                    border: '1px solid #ddd'
                                }}>
                                    {aiFeedback.strengths.map((item, index) => <li key={index} style={{ marginBottom: '8px' }}>{item}</li>)}
                                </ul>
                            </div>
                            
                            <div style={{ flex: 1 }}>
                                <h3>👇 待改进</h3>
                                <ul style={{ 
                                    padding: '15px', 
                                    backgroundColor: '#fff',
                                    borderRadius: '4px',
                                    border: '1px solid #ddd'
                                }}>
                                    {aiFeedback.weaknesses.map((item, index) => <li key={index} style={{ marginBottom: '8px' }}>{item}</li>)}
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div style={{ 
                        flex: '0 0 200px', 
                        textAlign: 'center',
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'center'
                    }}>
                        <h3>🏆 综合得分</h3>
                        <div style={{ 
                            fontSize: '4rem', 
                            fontWeight: 'bold', 
                            color: aiFeedback.score > 80 ? '#4CAF50' : aiFeedback.score > 60 ? '#FF9800' : '#F44336'
                        }}>
                            {aiFeedback.score}
                        </div>
                        <div style={{ 
                            marginTop: '10px',
                            padding: '10px',
                            backgroundColor: aiFeedback.score > 80 ? '#E8F5E9' : aiFeedback.score > 60 ? '#FFF3E0' : '#FFEBEE',
                            borderRadius: '4px',
                            color: aiFeedback.score > 80 ? '#388E3C' : aiFeedback.score > 60 ? '#F57C00' : '#D32F2F'
                        }}>
                            {aiFeedback.score > 80 ? '优秀' : aiFeedback.score > 60 ? '良好' : '需要改进'}
                        </div>
                    </div>
                </div>
            )}

            {error && (
                <div style={{ 
                    padding: '15px', 
                    backgroundColor: '#ffebee', 
                    color: '#c62828', 
                    borderRadius: '4px',
                    marginBottom: '20px',
                    border: '1px solid #ffcdd2'
                }}>
                    ❌ 错误: {error}
                </div>
            )}
        </div>
    );
}

export default FeynmanRecordPage;